<template>
  <div class="modify-order-no-box">
    <el-form :model="ruleModifyOrderNoForm" :rules="ruleModifyOrderNo" ref="ruleModifyOrderNoForm" class="modify-order-no">
      <el-form-item label="出库仓库" v-if="type !== 'modifyOrderNoOneTui'">
        <el-select v-model="ruleModifyOrderNoForm.commWarehouseId" filterable clearable placeholder="请选择出库仓库（选填）">
          <el-option :label="item.name" :value="item.id" v-for="(item, index) in commWarehouseList" :key="index"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="物流公司" prop="logisticsCompany">
        <el-select v-model="ruleModifyOrderNoForm.logisticsCompany" filterable clearable placeholder="请选择物流公司">
          <el-option :label="item.dictName" :value="item.dictId" v-for="(item, index) in dictionaries.courier_company" :key="index"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="物流单号" prop="logisticsNumber">
        <el-input  oninput ="value=value.replace(/[^\w]/g,'')" placeholder="请填写物流单号" v-model.trim="ruleModifyOrderNoForm.logisticsNumber"></el-input>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
export default {
  name: 'ModifyOrderNo',
  props: {
    type: {
      type: String,
      default: 'modifyOrderNoOne' // 类型（1退货；2换货） 参数值 ： modifyOrderNoOne modifyOrderNoTwo
    },
    source: { // 来源
      type: String,
      default: ''
    },
    afterId: {
      type: String,
      default: ''
    },
    orderObj: {
      type: Object,
      default () {
        return {}
      }
    }
  },
  data () {
    return {
      commWarehouseList: [],
      dictionaries: { // 物流公司编号
        courier_company: [] // 状态
      },
      ruleModifyOrderNoForm: {
        commWarehouseId: '',
        logisticsCompany: '',
        logisticsNumber: ''
      },
      ruleModifyOrderNo: {
        logisticsCompany: [{ required: true, message: '请选择物流公司', trigger: 'change' }],
        logisticsNumber: [{ required: true, message: '请输入物流单号', trigger: 'blur' }]
      }
    }
  },
  watch: {
    orderObj (val) {
      console.log(val, 'val')
      // （物流信息）订单状态信息查询
      if (val.orderId) {
        this.getLogisticsStatusByOrderId(val)
      }
    },
    ruleModifyOrderNoForm () {
      this.getLogisticsStatusByOrderId(this.orderObj.orderId)
    },
    deep: true // 为true，表示深度监听
  },
  computed: {
    customClass () {}
  },
  created () {
    // this.type === 'fullscreen' && (this.fullscreen = true)
    this.getCommWarehouse()
    // 获取字典值
    for (const type in this.dictionaries) { this.getDictionaries(type) }
  },
  mounted () {
    this.$nextTick(() => {
      const orderObj = this.orderObj
      // const orderId = orderObj.orderId ? orderObj.orderId : orderObj.afterNo
      // console.log(orderObj, orderId)
      // （物流信息）订单状态信息查询
      if (orderObj.orderId) {
        this.getLogisticsStatusByOrderId(orderObj)
      }
      this.$forceUpdate()
      console.log(this.type)
    })
  },
  methods: {
    // 获取字典数据
    getDictionaries (type) {
      if (type && this.dictionaries[type].length > 0) { return }
      const params = { groupId: type }
      this.$api.dictionaries(params).then((res) => {
        this.dictionaries[type] = res.data
      }).catch((err) => {
        console.log(err)
      })
    },
    // （物流信息）订单状态信息查询
    getLogisticsStatusByOrderId (orderObj) {
      const source = this.source
      // console.log(orderObj)
      const isAction = true
      for (const key in orderObj) {
        if (key === 'logisticsNumber') {
          // isAction = false
          break
        }
      }
      console.log(orderObj, isAction)
      if (isAction) {
        const params = { id: orderObj.orderId }
        this.$api.getLogisticsStatusByOrderId(params).then((res) => {
          // this.stepProgress.records = res.data.data
          const resData = res.data
          if (resData.logisticsCompany && resData.logisticsNumber) {
            this.ruleModifyOrderNoForm.commWarehouseId = resData.commWarehouseId // 仓库id
            this.ruleModifyOrderNoForm.logisticsCompany = resData.logisticsCompany // 物流公司编号
            this.ruleModifyOrderNoForm.logisticsNumber = resData.logisticsNumber // 物流单号
            this.ruleModifyOrderNoForm.status = resData.status // 物流单号
            console.log(res.data)
          } else {
            this.$refs['ruleModifyOrderNoForm'].resetFields()
          }
        }).catch((err) => {
          this.stepProgress = {}
          console.log(err)
        })
      } else {
        this.$refs['ruleModifyOrderNoForm'].resetFields()
        this.ruleModifyOrderNoForm.commWarehouseId = orderObj.commWarehouseId // 仓库id
        this.ruleModifyOrderNoForm.logisticsCompany = orderObj.logisticsCompany // 物流公司编号
        this.ruleModifyOrderNoForm.logisticsNumber = orderObj.logisticsNumber // 物流单号
        this.ruleModifyOrderNoForm.status = orderObj.status // 物流单号
      }
    },
    getCommWarehouse () {
      const params = { pageNo: 1, pageSize: 10000 }
      this.$api.commWarehouse(params).then((res) => {
        // console.log(res, '出库仓库')
        this.commWarehouseList = res.data.list
      }).catch((err) => {
        console.log(err)
      })
    },
    submit () {
      this.$refs['ruleModifyOrderNoForm'].validate((valid) => {
        if (valid) {
          const params = Object.assign({}, this.ruleModifyOrderNoForm)
          const type = this.type
          params.typeFlag = type === 'modifyOrderNoOne' || type === 'modifyOrderNoOneTui' ? 1 : 2 // 类型（1退货；2换货）
          if (JSON.stringify(this.orderObj) !== '{}') { params.afterId = Number(this.orderObj.id) }
          if (this.afterId) { params.afterId = this.afterId }// --单独传id是未了配合另一个页面
          params.logisticsNumber = params.logisticsNumber.trim() // 去除前后空格
          let actionFun
          if (this.source === 'service') { // 客服订单 有使用中
            actionFun = this.$api.updateLogistics
            params.orderNo = this.orderObj.orderNo
          } else {
            actionFun = this.$api.afterUpdateLogistics
          }
          actionFun(params).then((res) => {
            // code === 104  表示失败
            if (res.code === 0 && res.code !== 104) {
              this.$refs['ruleModifyOrderNoForm'].resetFields()
              this.$emit('submitState', true, params.typeFlag)
              this.$message({
                type: 'success',
                message: '操作成功!'
              })
            } else {
              this.$refs['ruleModifyOrderNoForm'].resetFields()
              this.$emit('submitState', true, params.typeFlag)
            }
          }).catch((err) => {
            this.$emit('submitState', false)
            console.log(err)
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    }
  }
}
</script>

<style lang="scss">
.modify-order-no{
  .el-form-item{
    .el-form-item__label{
      width: 80px;
    }
    .el-form-item__content{
      width: calc( 100% - 100px);
      float: left;
      .el-select{
        width: 100%;
      }
    }
  }
}

</style>

<!--//组件调用-->
<!--<dialog-a ref="dialogaaa" />-->
<!--//组件引用-->
<!--import DialogA from './Dialog.vue'-->
<!--//注册组件-->
<!--components: {-->
<!--DialogA-->
<!--},-->
<!--//打开Dialog-->
<!--this.$refs.dialogaaa.open()-->

<!--//组件内部定义逻辑，注意dialog隐藏显示是show不是if,所以初次加载逻辑不能写在created里边-->
<!--&lt;!&ndash;  Dialog&ndash;&gt;-->
<!--<template>-->
<!--  <base-dialog ref="dialog"-->
<!--               width="800px"-->
<!--               type="form"-->
<!--               :fullscreen="true"-->
<!--               :title="title"-->
<!--               footer-->
<!--               :before-close="close"-->
<!--               @closed="closed">-->
<!--    <template slot="body">-->
<!--      <div>tree</div>-->
<!--    </template>-->
<!--    <template slot="footer">-->
<!--      <el-button type="primary" @click="save">保存</el-button>-->
<!--      <el-button @click="close()">取消</el-button>-->
<!--    </template>-->
<!--  </base-dialog>-->
<!--</template>-->

<!--<script>-->
<!--import BaseDialog from '@/components/BaseDialog.vue'-->
<!--export default {-->
<!--  components: {-->
<!--    BaseDialog-->
<!--  },-->
<!--  data() {-->
<!--    return {-->
<!--      title: ''-->
<!--    }-->
<!--  },-->
<!--  computed: {-->

<!--  },-->
<!--  created() {},-->
<!--  methods: {-->
<!--    open() {-->
<!--      this.$refs.dialog.open()-->
<!--      this.title = '新增XXXXXX'-->
<!--    },-->
<!--    close() {-->
<!--      this.$refs.dialog.close()-->
<!--    },-->
<!--    closed() {},-->
<!--    save() {}-->
<!--  }-->
<!--}-->
<!--</script>-->
<!--<style lang='scss' scoped>-->

<!--</style>-->
